/**********************************************************************
 Name:  TradeIncrementToPDAWS
 Purpose:Trad PDA主数据下载ws                                                            
-------                                                             
======================================================
History                                                            
-------                                                            
VERSION    AUTHOR                  DATE                 DETAIL                                
   1.0 -        
   2.0-          huangxiaojiang       2011-04-25        增加了survey数据的返回     
   3.0-          huangxiaojiang       2011-06-24        增加了折扣率数据的返回      
*********************************** ************************************/
global with sharing class TradeIncrementToPDAWS
{
   //survey class
   global with sharing class SurveyEntry{
         //survey数据相关属性
         WebService List<TIMBASURVEYS__Recipient__c>   RecipientList{get;set;}
         WebService List<TIMBASURVEYS__Survey__c>   SurveyList{get;set;}
         WebService List<TIMBASURVEYS__SurveyQuestion__c>   QuestionList{get;set;}
         WebService List<TIMBASURVEYS__AnswerOption__c>   AnswerOptionList{get;set;}         
   }
  
  
    global with sharing class TradeEntry {
        WebService  Boolean resetPDA{get;set;}

        WebService List<Account> InsertAccount{get;set;}
        WebService List<Account> UpdateAccount{get;set;}
        WebService List<Id> DeleteAccount{get;set;}
         
        WebService List<Distributor__c> InsertDistributor{get;set;}
        WebService List<Distributor__c> updateDistributor{get;set;}
        WebService List<Id> deleteDistributor{get;set;}
        
        WebService List<Product2> InsertProduct{get;set;}
        WebService List<Product2> UpdateProduct{get;set;}
        WebService List<Id> DeleteProduct{get;set;}
         
        WebService List<Hospital__c> InsertHospital{get;set;}
        WebService List<Hospital__c> UpdateHospital{get;set;}
        WebService List<Id> DeteleHospital{get;set;}
          
      global TradeEntry()
      {
        resetPDA=false;
        
        InsertAccount=new List<Account>();
        UpdateAccount=new List<Account>();
        DeleteAccount=new List<Id>();
        
        InsertDistributor=new List<Distributor__c>();
        updateDistributor=new List<Distributor__c>();
        deleteDistributor=new List<Id>();
        
        InsertProduct=new List<Product2>();
        UpdateProduct=new List<Product2>();
        DeleteProduct=new List<Id>();
        
        InsertHospital=new List<Hospital__c>();
        UpdateHospital=new List<Hospital__c>();
        DeteleHospital=new List<Id>();
        
      }
      
   public  Map<Id,Account> getAccountMap 
    {
        get
        {
            Map<Id,Account> mapAccount=new Map<Id,Account>([select Id,OutletArea__c,Name,City__c,City__r.Name,Outlet_Code__c,
                                                            Chain_Customer__c,Outlet_Type__c,ChannelGroup__c,Channel__c,
                                                            Outlet_Address__c,Contact__c,Nearby_Hospital__c,ContactPhoneNumber__c,
                                                            Outlet_Area__c,No_of_checkout__c,Around_Hospital_Or_Not__c,
                                                            Distributor_Name__c,DMC_Chain_Customer__c,With_NC_or_not__c,
                                                            Active_Status__c,LastModifiedDate,OutletCode__c,IsConfirm__c  
                                                            from Account]);
            return mapAccount;
        }
    }
    
    public  Map<Id,Distributor__c> getDistributorMap
    {
        get
        {
             Map<Id,Distributor__c> mapDistributor=new Map<Id,Distributor__c>([Select Distributor_Code__c,Id,LastModifiedDate,Name 
                                                                             from Distributor__c ]);
            return mapDistributor;
        }
    }
    
    public  Map<Id,Product2> getProductMap
    {
        get
        {
             Map<Id,Product2> mapProduct=new Map<Id,Product2>([select ProductCode,Name,Brand__c,Barcode__c,Id,Product_English_Name__c,Brand_Group__c,
                                             Product_Stage__c,Product_Type__c,Product_Package__c,Pack_Size_C__c ,Product_Unit_Volume__c,
                                             Product_Shipment_Price__c,Distributor_Listing_Price_After_Tax__c,LastModifiedDate,
                                             Suggested_Retail_Price__c,ExfactoryPricePretax__c,ExfactoryPriceAfterTax__c
                                             from Product2 where IsActive=true and IsDeleted=false and Pack_Size_C__c>0 and Product_Type__c<>'' 
                                             and Product_Type__c<>'PE Sample']);
            return mapProduct;
        }
    }
    public  Map<Id,Hospital__c> getHospitalMap
    {
        get
        {
            Map<Id,Hospital__c> mapHospital=new Map<Id,Hospital__c>([Select HospitalCode__c,Id,Name from Hospital__c where Active__c=true]);
            
            return mapHospital;
        }
    }
    
    public  List<PDAMasterDataBackup__c> GetBackUpDataList
    {
        get
        {
            return [select Id__c,Type__c,createdDate from PDAMasterDataBackup__c];
        }
    }
}


    WebService static TradeEntry getIncremental(Boolean downloadAll)
    {
        if(downloadAll==false)//更新数据
        {
            return GetUpdateData();
        }
        else//下载所有的数据
        { 
            return CreateBackUpData();
        }
    }
    
    public static TradeEntry GetUpdateData()
    {
        TradeEntry getData=new TradeEntry();
        Datetime dt;
        Map<Id,PDAMasterDataBackup__c> BackupDataList=new Map<Id,PDAMasterDataBackup__c>();//获取备份表数据
        for(PDAMasterDataBackup__c pda:getData.GetBackUpDataList)
        {
            BackupDataList.put(pda.ID__c,pda);
        }
        
        if(BackupDataList==NULL || BackupDataList.size()==0)//如果没有值返回一个状态给PDA
        {
            getData.resetPDA=true;
            return getData;
        }
        else
        {
            //************修改和删除
            Map<Id,Account> getAccountMap=getData.getAccountMap;
            Map<Id,Distributor__c> getDistributorMap=getData.getDistributorMap;
            Map<Id,Product2> getProductMap=getData.getProductMap;
            Map<Id,Hospital__c> getHospitalMap=getData.getHospitalMap;
            
            for(PDAMasterDataBackup__c pmd:BackupDataList.values())
            {
                //outlet
                if(pmd.Type__c=='Outlet')
                {
                   if(getAccountMap.containsKey(pmd.ID__c))
                   {
                        if(getAccountMap.get(pmd.ID__c).LastModifiedDate > pmd.createdDate)//修改
                        {
                            getData.UpdateAccount.add(getAccountMap.get(pmd.ID__c));
                        }
                   }
                   else//删除
                   {
                        getData.DeleteAccount.add(pmd.ID__c);
                   }
                }
               
               //Distributor
               if(pmd.Type__c=='Distributor')
               {
                   if(getDistributorMap.containsKey(pmd.ID__c))
                   {
                        if(getDistributorMap.get(pmd.ID__c).LastModifiedDate > pmd.createdDate)//修改
                            getData.updateDistributor.add(getDistributorMap.get(pmd.ID__c));
                   }
                   else//删除
                   {
                        getData.deleteDistributor.add(pmd.ID__c);
                   }
               }
               
               //Product
               if(pmd.Type__c=='Product')
               {
                   if(getProductMap.containsKey(pmd.ID__c))
                   {
                        if(getProductMap.get(pmd.ID__c).LastModifiedDate > pmd.createdDate)//修改
                            getData.UpdateProduct.add(getProductMap.get(pmd.ID__c));
                   }
                   else//删除
                   {
                        getData.DeleteProduct.add(pmd.ID__c);
                   }
               }
               
               //Hospital
               if(pmd.Type__c=='Hospital_T')
               {
                   if(!getHospitalMap.containsKey(pmd.ID__c))
                   {
                        getData.DeteleHospital.add(pmd.ID__c);//删除
                   }
                   else
                   {
                        dt=pmd.createdDate;//记录时间
                   }
               }
            }
            
            //******************新增
            for(Account acc:getAccountMap.values())
            {
                //outlet
                if(!BackupDataList.containsKey(acc.Id))
                {
                    getData.InsertAccount.add(acc);
                }
            }
            
            //Distributor
            for(Distributor__c dis:getDistributorMap.values())
            {
                if(!BackupDataList.containsKey(dis.Id))
                {
                    getData.InsertDistributor.add(dis);
                }
            }
            
            //Product
            for(Product2 pro:getProductMap.values())
            {
                if(!BackupDataList.containsKey(pro.Id))
                {
                    getData.InsertProduct.add(pro);
                }
            }
            
            //Hospital_T
            for(Hospital__c hos:getHospitalMap.values())
            {
                if(!BackupDataList.containsKey(hos.Id))
                {
                    getData.InsertHospital.add(hos);
                }
            }
                  
            //hospital修改                                                                  
            getData.UpdateHospital=[Select HospitalCode__c,Id, Name from Hospital__c where Id in 
                                    (Select Hospital__c From HospitalChangeHistory__c Where
                                     Hospital__c in: BackupDataList.keySet() and CreatedDate >=: dt
                                     and Name = '医院重命名')];  
        
        }
         
        CreateAndDeleteBackUPPDAData();
        
        return getData;
    }
    
    public static TradeEntry CreateBackUpData()
    {
        TradeEntry getData=new TradeEntry();
        getData.InsertAccount=getData.getAccountMap.values();
        getData.InsertDistributor=getData.getDistributorMap.values();
        getData.InsertHospital=getData.getHospitalMap.values();
        getData.InsertProduct=getData.getProductMap.values();
        
        CreateAndDeleteBackUPPDAData();
                
        return getData;
    }
    
    //创建新的数据到备份表并且删除原先的数据
    @Future(callout=true)
    public static void CreateAndDeleteBackUPPDAData()
    {
        TradeEntry getData=new TradeEntry();
        List<PDAMasterDataBackup__c> BackDataList=new List<PDAMasterDataBackup__c>();
        
        for(Account acc:getData.getAccountMap.values())
        {
            BackDataList.add(new PDAMasterDataBackup__c(ID__c=acc.Id,Type__c='Outlet'));
        }
        
        for(Distributor__c dis:getData.getDistributorMap.values())
        {
            BackDataList.add(new PDAMasterDataBackup__c(ID__c=dis.Id,Type__c='Distributor'));
        }
        
        for(Product2 pro:getData.getProductMap.values())
        {
            BackDataList.add(new PDAMasterDataBackup__c(ID__c=pro.Id,Type__c='Product'));
        }
        
        for(Hospital__c hos:getData.getHospitalMap.values())
        {
            BackDataList.add(new PDAMasterDataBackup__c(ID__c=hos.Id,Type__c='Hospital_T'));
        }
        try
        {
            delete [select Id from PDAMasterDataBackup__c];
        }
        catch(Exception ex)
        {
            
        }
        
        insert BackDataList;
    }
    
    //返回survey数据
    Webservice static SurveyEntry getSurveyData(){
        
        SurveyEntry getData=new SurveyEntry ();
        getData.RecipientList=new List<TIMBASURVEYS__Recipient__c>();
        getData.SurveyList=new List<TIMBASURVEYS__Survey__c>();
        getData.QuestionList=new List<TIMBASURVEYS__SurveyQuestion__c>();
        getData.AnswerOptionList=new List<TIMBASURVEYS__AnswerOption__c>(); 

            
            getData.RecipientList=[select CreatedDate,Survey_Distribution__r.StartDate__c,Survey_Distribution__r.EndDate__c,Id,IsDeleted,
                Name,Outlet__c,TIMBASURVEYS__Survey__c,TakePhoto__c  from TIMBASURVEYS__Recipient__c
                where IsDeleted=:false and TIMBASURVEYS__Survey__c!=null and TIMBASURVEYS__Survey__r.TIMBASURVEYS__CollectingData__c=:true
                and Outlet__r.OwnerId=:UserInfo.getUserId()  
                and (TIMBASURVEYS__Collected__c=:false or TIMBASURVEYS__Survey__r.TIMBASURVEYS__AllowMultiFill__c=:true) 
                and Survey_Distribution__r.StartDate__c<=:date.today() and Survey_Distribution__r.EndDate__c>=:date.today()];
           
           if(getData.RecipientList.size()>0){
                set<id> sSurveyId=new set<id>();
                for(TIMBASURVEYS__Recipient__c rp:getData.RecipientList){
                    sSurveyId.add(rp.TIMBASURVEYS__Survey__c);
                }
                
                getData.SurveyList=[select CreatedById,CreatedDate,Id,IsDeleted,Name,TIMBASURVEYS__Description__c,TIMBASURVEYS__Status__c,TIMBASURVEYS__AllowMultiFill__c
                    from TIMBASURVEYS__Survey__c where id in:sSurveyId];
                 //防止dataloader直接删除survey   
                 sSurveyId.clear();   
                 for(TIMBASURVEYS__Survey__c s:getData.SurveyList){
                      sSurveyId.add(s.id);        
                 }    
                
                getData.QuestionList=[select CreatedDate,Id,IsDeleted,TIMBASURVEYS__AllowActiveBranching__c,TIMBASURVEYS__Columns__c,TIMBASURVEYS__HasChild__c,
                    TIMBASURVEYS__IsRequired__c,TIMBASURVEYS__ParentId__c,TIMBASURVEYS__Question__c,TIMBASURVEYS__QuestionComment__c,TIMBASURVEYS__QuestionTypeCode__c
                    ,TIMBASURVEYS__RowPlacement__c,TIMBASURVEYS__Survey__c from TIMBASURVEYS__SurveyQuestion__c where TIMBASURVEYS__Survey__c in:sSurveyId
                    and IsDeleted=:false order by TIMBASURVEYS__ParentId__c, TIMBASURVEYS__RowPlacement__c asc 
                    ];
                
                set<id>sQuesId=new set<id>();
                for(TIMBASURVEYS__SurveyQuestion__c q:getData.QuestionList){
                    sQuesId.add(q.id);
                }
                getData.AnswerOptionList=[select CreatedById,CreatedDate,Id,IsDeleted,Name,OwnerId,TIMBASURVEYS__IsPicklistValue__c,TIMBASURVEYS__numericRange__c,
                    TIMBASURVEYS__OptionValue__c,TIMBASURVEYS__Picklist__c,TIMBASURVEYS__Position__c,TIMBASURVEYS__ResponseType__c,TIMBASURVEYS__SurveyQuestion__c
                     from TIMBASURVEYS__AnswerOption__c where TIMBASURVEYS__SurveyQuestion__c in:sQuesId];
           }
          
           
        //}
        
        return getData;    
    }

    //返回经销商订单折扣率信息 by xiaojiang 6-24
    Webservice static string getOrderDiscount(){
    
        string strRet='';          
        //读取custom seting
         Map<String, OrderDiscount__c> mapOD=OrderDiscount__c.getAll();
         //获取值列表，一个名称对应3个值：cash，credit，promotion
         for(string keyName:mapOD.keySet()){
         
             OrderDiscount__c od=mapOD.get(keyName);
             strRet+='cash,'+od.cash__c+';';
             strRet+='credit,'+od.credit__c+';';
             strRet+='promotion,'+od.promotion__c;              
         }
        return strRet;
        
    }  
  //获取活动期间竟品费用信息
    Webservice static List<Activity_Competition_Brand_Detail__c> getCompetionBrandData(List<string> activityIdList)
    {
            
          List<Activity_Competition_Brand_Detail__c > acbdList=new List<Activity_Competition_Brand_Detail__c >();
          List<Activity_Competition_Brand_Detail__c> queryResultList=new List<Activity_Competition_Brand_Detail__c>();
          if(activityIdList!=NULL && activityIdList.size()>0)
          {
              queryResultList=[select id,ActivityId__c,Promotion_Type__c,ActivityType__c,
                                        OutletId__c,Money__c,Start_Date__c, End_Date__c,
                                        Display_Type__c,IsPerformance__c,SubmitASM__r.Approve_Type__c,
                                        SubmitASM__r.Approve_Description__c
                                        from Activity_Competition_Brand_Detail__c 
                                        where Start_Date__c<=:System.today()
                                         and  End_Date__c>=:System.today()
                                          and Start_Date__c!=NULL
                                         and SubmitASM__r.IsActive__c=true
                                         and ActivityId__c not in: activityIdList and 
                                        (Activity_Competition_Brand_Information__r.Activity_Information__r.Activity_Stage__c='总部已发起活动' 
                                         or Activity_Competition_Brand_Information__r.Activity_Information__r.Activity_Stage__c='SRTM已发起活动' 
                                         or Activity_Competition_Brand_Information__r.Activity_Information__r.Activity_Stage__c='SRTM已完成区域调整')];
          }
          else
          {
               queryResultList=[select id,ActivityId__c,Promotion_Type__c,ActivityType__c,
                                        OutletId__c,Money__c,Start_Date__c, End_Date__c,
                                        Display_Type__c,IsPerformance__c,SubmitASM__r.Approve_Type__c,
                                        SubmitASM__r.Approve_Description__c
                                        from Activity_Competition_Brand_Detail__c 
                                        where Start_Date__c<=:System.today()
                                         and  End_Date__c>=:System.today()
                                         and Start_Date__c!=NULL
                                         and SubmitASM__r.IsActive__c=true and
                                         (Activity_Competition_Brand_Information__r.Activity_Information__r.Activity_Stage__c='总部已发起活动' 
                                         or Activity_Competition_Brand_Information__r.Activity_Information__r.Activity_Stage__c='SRTM已发起活动' 
                                         or Activity_Competition_Brand_Information__r.Activity_Information__r.Activity_Stage__c='SRTM已完成区域调整')];
          }
          for(Activity_Competition_Brand_Detail__c rcbd:queryResultList)
           {
                if(rcbd.ActivityType__c!='KA')
                {
                    if((rcbd.SubmitASM__r.Approve_Type__c=='SRTM已审批' && rcbd.SubmitASM__r.Approve_Description__c=='同意')
                       || rcbd.SubmitASM__r.Approve_Type__c=='ASM已确认时间')  
                    {
                        acbdList.add(rcbd);
                    }
                }
                else
                {
                    if(rcbd.SubmitASM__r.Approve_Type__c=='ASM已提交')
                    {
                         acbdList.add(rcbd);
                    }
                }
            }
        return acbdList;
    }
    //获取订单数据
    Webservice static List<Resource_Allocation_Detail__c> getOrderData(string outletId)
    {
        List<Resource_Allocation_Detail__c> resList=new  List<Resource_Allocation_Detail__c>();
        for(Resource_Allocation_Detail__c rad:[select id,ActivityId__c,ActivityName__c,HasUsedResourceNumber__c,outletID__c,
                                                                              ProductId__c, ProductName__c,Resource_Quantity_Number__c,
                                                                              Participator_Detail_Area__r.Approve_Type__c,
                                                                              Participator_Detail_Area__r.Approve_Description__c,ActivityType__c
                                                                              from Resource_Allocation_Detail__c
                                                                              where outletID__c=:outletId.substring(0,15) 
                                                                              and Participator_Detail_Outlet__r.ActivityStartDate__c<=:System.today().addDays(21)
                                                                              and Participator_Detail_Outlet__r.ActivityEndDate__c>=:System.today()
                                                                              and Participator_Detail_Area__r.IsActive__c=true
                                                                               and (ActivityType__c='总部已发起活动' or ActivityType__c='SRTM已发起活动'
                                                                               or ActivityType__c='SRTM已完成区域调整')])
         {
              if(rad.ActivityType__c!='KA')
                {
                    if((rad.Participator_Detail_Area__r.Approve_Type__c=='SRTM已审批' && rad.Participator_Detail_Area__r.Approve_Description__c=='同意') 
                        || rad.Participator_Detail_Area__r.Approve_Type__c=='ASM已确认时间') 
                    {
                        resList.add(rad);
                    }
                }
                else
                {
                    if(rad.Participator_Detail_Area__r.Approve_Type__c=='ASM已提交')
                    {
                         resList.add(rad);
                    }
                }
         }
                                                                              
                  
             return resList;
    }
        /*static testmethod void test() 
    {
         Profile p=[select  id from profile where  name='Sales Rep - Trade' limit 1];        
         User u=new user(alias='hxj',email='xjhuang87@isoftstone.com',lastName='testing'        
         ,languageLocaleKey='zh_CN',localeSidkey='zh_CN' ,TimeZoneSidKey='Asia/Shanghai',EmailEncodingKey='UTF-8',        
         profileId=p.id,userName='xjhuang123@isoftstone.com');
         
        // User u = [select Id,name from user where FunctionDepartment__c =: 'Trade Sales' and Title__c =: 'Sales Rep' limit 1];
         System.runAs(u) {
             TradeIncrementToPDAWS.getIncremental(true);
             //TradeIncrementToPDAWS.CreateBackUpData();
         }
        
    }*/
   
}